<template>
  <div class="photo-preview">
    <!-- 顶部导航栏 -->
    <TopNavbar />

    <!-- 顶部操作区 -->
    <div class="preview-header">
      <div class="header-left">
        <button class="back-btn" @click="handleBack">
          <img src="@/assets/back/leftback01.png" alt="返回" class="back-icon" />
          <span class="back-text">返回</span>
        </button>
        <span class="task-title">{{ taskName }}</span>
      </div>

      <div class="header-right">
        <button class="cancel-btn" @click="handleCancel">取消</button>
        <button class="confirm-btn" @click="handleConfirm" :disabled="!taskName.trim()">确认</button>
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="content-area">
      <!-- 左侧图片预览区 -->
      <div class="preview-sidebar">
        <div class="preview-list">
          <div v-for="(photo, index) in photos" :key="index" class="preview-item"
            :class="{ active: currentIndex === index }" @click="selectPhoto(index)">
            <div class="preview-number">{{ index + 1 }}</div>
            <div class="preview-image">
              <!-- 显示实际的缩略图 -->
              <img v-if="photo.thumbnail" :src="photo.thumbnail" :alt="`第${index + 1}页`" class="thumbnail-img" />
            </div>
          </div>

          <!-- 再拍一页按钮 -->
          <div class="add-more-item" @click="handleAddMore">
            <div class="preview-number add-more-number">+</div>
            <div class="preview-image add-more-image">
              <div class="add-more-content">
                <div class="add-more-icon">
                  <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M14 2H6C4.9 2 4 2.9 4 4V20C4 21.1 4.89 22 5.99 22H18C19.1 22 20 21.1 20 20V8L14 2Z"
                      stroke="#8C9CAD" stroke-width="2" fill="none" />
                    <path d="M14 2V8H20" stroke="#8C9CAD" stroke-width="2" fill="none" />
                  </svg>
                </div>
                <div class="add-more-text">再拍一页</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧图片展示区 -->
      <div class="main-display">
        <div class="image-container">
          <!-- 主要图片显示区域 -->
          <div class="main-image">
            <!-- 显示实际的照片 -->
            <img v-if="currentPhoto && currentPhoto.fullImage" :src="currentPhoto.fullImage"
              :alt="`第${currentIndex + 1}页照片`" class="main-photo" />
            
          </div>
        </div>

        <!-- 页数进度展示 -->
        <div class="page-progress">
          <button class="nav-btn prev-btn" @click="prevPhoto" :disabled="currentIndex === 0">
            <span>‹</span>
          </button>
          <div class="current-page">{{ currentIndex + 1 }}</div>
          <span class="page-separator">/</span>
          <span class="total-pages">{{ totalPages }}</span>
          <button class="nav-btn next-btn" @click="nextPhoto" :disabled="currentIndex === totalPages - 1">
            <span>›</span>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import { type PhotoData } from '@/utils/photosDB'
import TopNavbar from '@/components/shared/Layout/TopNavbar.vue'

const router = useRouter()
const route = useRoute()

// Props
interface Props {
  photos?: string[]
  taskName?: string
}

const props = withDefaults(defineProps<Props>(), {
  photos: () => ['photo1', 'photo2', 'photo3', 'photo4'],
  taskName: '这里是教学任务名称'
})

// 响应式数据
const currentIndex = ref(0)
const photos = ref<PhotoData[]>([])
const taskName = ref('')
const context = ref(route.query.context as string || 'task-creation')

// 调试方法
const debugLocalStorage = () => {
  console.log('🔍 === PhotoPreview 调试信息 ===')
  console.log('🔍 localStorage keys:', Object.keys(localStorage))

  const currentSessionPhotosData = localStorage.getItem('currentSessionPhotosData')
  const currentSessionPhotoIds = localStorage.getItem('currentSessionPhotoIds')
  const capturedPhotosData = localStorage.getItem('capturedPhotosData')

  console.log('🔍 currentSessionPhotosData 存在:', !!currentSessionPhotosData)
  if (currentSessionPhotosData) {
    try {
      const parsed = JSON.parse(currentSessionPhotosData)
      console.log('🔍 currentSessionPhotosData 数量:', parsed.length)
      console.log('🔍 currentSessionPhotosData 详情:', parsed.map((p: any) => ({ id: p.id, timestamp: p.timestamp })))
    } catch (e) {
      console.log('🔍 currentSessionPhotosData 解析失败:', e)
    }
  }

  console.log('🔍 currentSessionPhotoIds:', currentSessionPhotoIds)
  console.log('🔍 capturedPhotosData:', capturedPhotosData)
  console.log('🔍 当前 photos.value.length:', photos.value.length)
  console.log('🔍 ========================')
}

// 从photos数据库加载照片数据
const loadPhotosFromStorage = async (forceRefresh = false) => {
  try {
    console.log('🔄 [loadPhotosFromStorage] 开始加载照片数据, forceRefresh:', forceRefresh)
    console.log('🔄 [loadPhotosFromStorage] 当前 photos.value 长度:', photos.value.length)

    // 保存当前已有的照片数据
    const existingPhotos = forceRefresh ? [] : [...photos.value]
    console.log('🔄 [loadPhotosFromStorage] 保存的现有照片数量:', existingPhotos.length)
    console.log('🔄 [loadPhotosFromStorage] 现有照片详情:', existingPhotos.map(p => ({ id: p.id, timestamp: p.timestamp })))

    // 清理可能存在的历史 sessionStorage 数据
    sessionStorage.removeItem('capturedPhotosData')
    console.log('🔄 [loadPhotosFromStorage] 清理历史 sessionStorage 数据')

    // 优先从 localStorage 读取当前会话的照片数据
    const currentSessionPhotosDataStr = localStorage.getItem('currentSessionPhotosData')
    let targetPhotos = []

    console.log('🔄 [loadPhotosFromStorage] 检查 localStorage 数据:', {
      hasData: !!currentSessionPhotosDataStr,
      dataLength: currentSessionPhotosDataStr?.length || 0,
      existingPhotosCount: existingPhotos.length
    })

    if (currentSessionPhotosDataStr) {
      // 从 localStorage 读取照片数据
      try {
        const currentSessionPhotosData = JSON.parse(currentSessionPhotosDataStr)
        console.log('📸 [localStorage] 从 localStorage 读取照片数据:', currentSessionPhotosData.length, '张照片')
        console.log('📸 [localStorage] 原始照片数据:', currentSessionPhotosData)

        // 直接使用 localStorage 中的照片数据，不需要查询数据库
        interface LocalStoragePhoto {
          id: string
          thumbnail: string
          fullImage: string
          timestamp: number
        }

        targetPhotos = currentSessionPhotosData.map((photo: LocalStoragePhoto) => ({
          id: photo.id,
          taskId: 'temp-' + Date.now(), // 临时任务ID
          studentId: '',
          isCreate: true,
          thumbnail: photo.thumbnail,
          fullImage: photo.fullImage,
          timestamp: photo.timestamp,
          teacherID: '',
          fileName: `photo_${photo.timestamp}.jpg`,
          fileSize: 0,
          description: ''
        }))
        console.log('📸 [localStorage] 转换后的照片数据:', targetPhotos.length, '张照片')
        console.log('📸 [localStorage] 转换后的照片详情:', targetPhotos.map((p: any) => ({ id: p.id, timestamp: p.timestamp })))
      } catch (parseError) {
        console.error('❌ [localStorage] 解析 localStorage 照片数据失败:', parseError)
        targetPhotos = []
      }
    } else {
      // 如果 localStorage 中没有数据，尝试从数据库加载（兼容旧逻辑）
      console.log('🗄️ [数据库] localStorage 中没有照片数据，尝试从数据库加载')

      const { photosStorage } = await import('@/utils/photosDB')
      await photosStorage.init()

      const sessionPhotoIdsStr = route.query.sessionPhotoIds as string
      if (sessionPhotoIdsStr) {
        try {
          const sessionPhotoIds = JSON.parse(sessionPhotoIdsStr)
          console.log('🗄️ [数据库] 从数据库加载指定会话的照片ID:', sessionPhotoIds)

          const allPhotos = await photosStorage.getAllPhotos()
          targetPhotos = allPhotos.filter(photo => sessionPhotoIds.includes(photo.id))
          console.log('🗄️ [数据库] 从数据库找到的会话照片:', targetPhotos.length, '张')
          console.log('🗄️ [数据库] 数据库照片详情:', targetPhotos.map((p: PhotoData) => ({ id: p.id, timestamp: p.timestamp })))
        } catch (parseError) {
          console.error('❌ [数据库] 解析会话照片ID失败:', parseError)
          targetPhotos = []
        }
      } else {
        console.log('⚠️ [数据库] 没有指定会话ID，不加载任何照片')
        targetPhotos = []
      }
    }

    // 转换新照片为PhotoPreview需要的格式
    console.log('🔄 [转换] 开始转换 targetPhotos，数量:', targetPhotos.length)
    const newPhotos = targetPhotos.map((photo: PhotoData) => ({
      id: photo.id,
      taskId: photo.taskId,
      studentId: photo.studentId,
      isCreate: photo.isCreate,
      thumbnail: photo.thumbnail,
      fullImage: photo.fullImage,
      timestamp: photo.timestamp,
      teacherID: photo.teacherID,
      fileName: photo.fileName,
      fileSize: photo.fileSize,
      description: photo.description
    }))
    console.log('🔄 [转换] 转换后的新照片数量:', newPhotos.length)
    console.log('🔄 [转换] 新照片详情:', newPhotos.map((p: any) => ({ id: p.id, timestamp: p.timestamp })))

    // 合并现有照片和新照片，去重（基于ID）
    console.log('🔄 [合并] 开始合并照片')
    console.log('🔄 [合并] 现有照片数量:', existingPhotos.length)
    console.log('🔄 [合并] 新照片数量:', newPhotos.length)

    const allPhotos = [...existingPhotos]
    console.log('🔄 [合并] 初始 allPhotos 数量:', allPhotos.length)

    newPhotos.forEach((newPhoto: PhotoData) => {
      const existingIndex = allPhotos.findIndex((existing: PhotoData) => existing.id === newPhoto.id)
      console.log(`🔄 [合并] 处理新照片 ID: ${newPhoto.id}, 是否已存在: ${existingIndex !== -1}`)
      if (existingIndex === -1) {
        // 新照片，添加到列表
        allPhotos.push(newPhoto)
        console.log(`✅ [合并] 添加新照片 ID: ${newPhoto.id}, 当前总数: ${allPhotos.length}`)
      } else {
        // 已存在的照片，更新数据
        allPhotos[existingIndex] = newPhoto
        console.log(`🔄 [合并] 更新现有照片 ID: ${newPhoto.id}`)
      }
    })

    console.log('🔄 [合并] 合并完成，总照片数量:', allPhotos.length)
    console.log('🔄 [合并] 合并后照片详情:', allPhotos.map((p: any) => ({ id: p.id, timestamp: p.timestamp })))

    // 按时间戳排序，确保最新的照片在前面
    const sortedPhotos = allPhotos.sort((a: PhotoData, b: PhotoData) => b.timestamp - a.timestamp)
    console.log('🔄 [排序] 排序后照片数量:', sortedPhotos.length)
    console.log('🔄 [排序] 排序后照片详情:', sortedPhotos.map((p: any) => ({ id: p.id, timestamp: p.timestamp })))

    photos.value = sortedPhotos
    console.log('✅ [完成] 成功设置 photos.value:', photos.value.length, '张照片')
    console.log('✅ [完成] 最终 photos.value 详情:', photos.value.map((p: any) => ({ id: p.id, timestamp: p.timestamp })))

    // 获取当前索引，确保不超出范围
    if (route.query.currentIndex && !forceRefresh) {
      const index = parseInt(route.query.currentIndex as string) || 0
      currentIndex.value = Math.min(index, Math.max(0, photos.value.length - 1))
    } else {
      // 强制刷新时或没有指定索引时，显示第一张照片（最新的）
      currentIndex.value = 0
    }

    // 获取任务名称
    taskName.value = (route.query.taskName as string) || props.taskName

    console.log('照片加载完成，共', photos.value.length, '张照片')
  } catch (error) {
    console.error('从photos数据库加载照片失败:', error)
    photos.value = []
    taskName.value = props.taskName
    currentIndex.value = 0
  }
}

// 计算属性
const totalPages = computed(() => photos.value.length)
const currentPhoto = computed(() => photos.value[currentIndex.value])

// 方法
const handleBack = () => {
  router.go(-1)
}

const handleCancel = async () => {
  // 显示取消确认对话框
  try {
    await ElMessageBox.confirm(
      '取消后当前照片将不会保存？',
      // '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        customClass: 'cancel-confirm-dialog'
      }
    )

    // 用户确认取消，清理照片数据
    try {
      const { photosStorage } = await import('@/utils/photosDB')
      await photosStorage.init()
      await photosStorage.clearPhotos()
      console.log('照片数据已清理')
    } catch (error) {
      console.error('清理照片数据失败:', error)
    }

    router.go(-1)
  } catch {
    // 用户点击了取消，不执行任何操作
  }
}

const handleConfirm = async () => {
  console.log('确认选择的照片:', photos.value.length, '张')
  console.log('当前路由查询参数:', route.query)

  try {
    const taskId = route.query.taskId as string
    const studentId = route.query.studentId as string
    const fromRoute = route.query.fromRoute as string
    const returnTo = route.query.returnTo as string

    console.log('处理确认，context:', context.value, 'taskId:', taskId, 'studentId:', studentId, 'fromRoute:', fromRoute)

    if (context.value === 'task-creation') {
      console.log('进入任务创建流程 - 返回TaskCreationWizard第二步')

      // 只传递当前会话的照片数据，不包含历史照片
      let currentSessionPhotos: any[] = []

      if (photos.value.length > 0) {
        // 使用当前显示的照片数据（已经过滤了历史照片）
        currentSessionPhotos = photos.value
        console.log('PhotoPreview: 当前会话照片数据:', currentSessionPhotos.length, '张照片')
      } else {
        console.log('PhotoPreview: 没有当前会话的照片数据')
      }

      // 将当前会话的照片数据存储到 localStorage，供TaskCreationWizard使用
      const photoDataForWizard = currentSessionPhotos.map(photo => photo.fullImage)
      localStorage.setItem('capturedPhotosData', JSON.stringify(photoDataForWizard))
      console.log('PhotoPreview: 照片数据已存储到 localStorage，供TaskCreationWizard使用:', photoDataForWizard.length, '张照片')

      ElMessage.success('照片已确认，返回任务创建页面')

      console.log('准备跳转回TaskCreationWizard第二步')
      // 跳转回TaskCreationWizard的第二步
      try {
        await router.push({
          path: '/teacher/teaching-tasks/create',
          query: {
            step: '1', // 第二步（从0开始计数）
            hasPhotos: 'true'
          }
        })
        console.log('成功跳转回TaskCreationWizard第二步')
      } catch (error) {
        console.error('跳转回TaskCreationWizard失败:', error)
        // 如果跳转失败，尝试使用name方式跳转
        try {
          await router.push({
            name: 'task-creation-wizard',
            query: {
              step: '1',
              hasPhotos: 'true'
            }
          })
          console.log('使用name方式成功跳转回TaskCreationWizard第二步')
        } catch (nameError) {
          console.error('使用name方式跳转也失败:', nameError)
          // 最后尝试直接跳转到任务创建页面，保持查询参数
          ElMessage.warning('跳转失败，直接返回任务创建页面')
          router.push({
            path: '/teacher/teaching-tasks/create',
            query: {
              step: '1',
              hasPhotos: 'true'
            }
          })
        }
      }

    } else if (context.value === 'task-detail-edit') {
      // 从任务详情页面的学生作业上传来的，直接返回任务详情页面
      ElMessage.success('学生作业照片已保存')

      // 返回任务详情页面，传递照片数据
      router.push({
        name: 'task-detail',
        params: {
          id: taskId
        },
        query: {
          fromPhotoPreview: 'true',
          studentId: studentId,
          photoUpdated: 'true'
        }
      })
    } else if (fromRoute === 'create-task-wizard') {
      // 创建教学任务流程：PhotoPreview -> TaskCreationSuccess
      console.log('从创建教学任务来的，跳转到任务创建成功页面')
      ElMessage.success('教学任务创建成功！')

      router.push({
        path: '/teacher/teaching-tasks/success',
        query: {
          taskName: taskName.value,
          taskId: taskId,
          fromPhotoPreview: 'true'
        }
      })
    } else if (fromRoute === 'homework-submission-detail' && returnTo === 'grading-history') {
      // 题目详情的"再拍一张"：PhotoPreview -> GradingHistory
      console.log('从题目详情的再拍一张来的，返回历史批改记录页面')
      ElMessage.success('照片已更新')

      router.push({
        path: '/teacher/homework-review/history',
        query: {
          fromPhotoPreview: 'true',
          photoUpdated: 'true'
        }
      })
    } else {
      // 其他情况，返回上一页
      ElMessage.success('照片已保存')
      router.back()
    }
  } catch (error) {
    console.error('保存照片失败:', error)
    ElMessage.error('保存照片失败，请重试')
  }
}

const selectPhoto = (index: number) => {
  currentIndex.value = index
}

const handleAddMore = () => {
  console.log('📷 [handleAddMore] 点击再拍一张按钮')
  console.log('📷 [handleAddMore] 当前照片数量:', photos.value.length)
  console.log('📷 [handleAddMore] 当前照片详情:', photos.value.map((p: any) => ({ id: p.id, timestamp: p.timestamp })))

  const queryParams = {
    returnTo: 'photo-preview',
    taskName: taskName.value,
    context: context.value,
    taskId: route.query.taskId,
    studentId: route.query.studentId,
    fromRoute: route.query.fromRoute,
    currentIndex: currentIndex.value.toString()
  }

  console.log('📷 [handleAddMore] 跳转参数:', queryParams)

  // 跳转到拍照页面继续拍摄
  router.push({
    name: 'camera-capture',
    query: queryParams
  })
}

// 上一张照片
const prevPhoto = () => {
  if (currentIndex.value > 0) {
    currentIndex.value--
  }
}

// 下一张照片
const nextPhoto = () => {
  if (currentIndex.value < photos.value.length - 1) {
    currentIndex.value++
  }
}

// 页面可见性变化时刷新数据
const handleVisibilityChange = () => {
  console.log('👁️ [可见性] 页面可见性变化, document.hidden:', document.hidden)
  if (!document.hidden) {
    // 页面变为可见时，检查是否从拍照页面返回
    const currentSessionPhotosDataStr = localStorage.getItem('currentSessionPhotosData')
    if (currentSessionPhotosDataStr) {
      try {
        const currentSessionPhotosData = JSON.parse(currentSessionPhotosDataStr)
        const localStorageIds = currentSessionPhotosData.map((p: any) => p.id).sort()
        const currentIds = photos.value.map(p => p.id).sort()
        const idsChanged = JSON.stringify(localStorageIds) !== JSON.stringify(currentIds)

        console.log('👁️ [可见性] localStorage 照片IDs:', localStorageIds)
        console.log('👁️ [可见性] 当前显示照片IDs:', currentIds)
        console.log('👁️ [可见性] 照片IDs是否变化:', idsChanged)

        if (idsChanged || currentSessionPhotosData.length !== photos.value.length) {
          console.log('👁️ [可见性] 检测到照片变化，重新加载')
          loadPhotosFromStorage(false)
        } else {
          console.log('👁️ [可见性] 照片无变化，跳过重新加载')
        }
      } catch (e) {
        console.log('👁️ [可见性] 解析失败，重新加载')
        loadPhotosFromStorage(false)
      }
    } else {
      console.log('👁️ [可见性] 页面变为可见，开始刷新照片数据')
      loadPhotosFromStorage(false)
    }
  }
}

// 窗口获得焦点时刷新数据
const handleWindowFocus = () => {
  console.log('🎯 [焦点] 窗口获得焦点，开始刷新照片数据')

  // 检查 localStorage 中的照片是否有变化
  const currentSessionPhotosDataStr = localStorage.getItem('currentSessionPhotosData')
  if (currentSessionPhotosDataStr) {
    try {
      const currentSessionPhotosData = JSON.parse(currentSessionPhotosDataStr)
      const localStorageCount = currentSessionPhotosData.length
      const currentCount = photos.value.length

      console.log('🎯 [焦点] localStorage 照片数量:', localStorageCount)
      console.log('🎯 [焦点] 当前显示照片数量:', currentCount)

      // 检查照片ID是否有变化
      const localStorageIds = currentSessionPhotosData.map((p: any) => p.id).sort()
      const currentIds = photos.value.map(p => p.id).sort()
      const idsChanged = JSON.stringify(localStorageIds) !== JSON.stringify(currentIds)

      console.log('🎯 [焦点] localStorage 照片IDs:', localStorageIds)
      console.log('🎯 [焦点] 当前显示照片IDs:', currentIds)
      console.log('🎯 [焦点] 照片IDs是否变化:', idsChanged)

      if (localStorageCount !== currentCount || idsChanged) {
        console.log('🎯 [焦点] 检测到照片变化，重新加载')
        loadPhotosFromStorage(false)
      } else {
        console.log('🎯 [焦点] 照片无变化，跳过重新加载')
      }
    } catch (e) {
      console.log('🎯 [焦点] 解析 localStorage 失败，重新加载')
      loadPhotosFromStorage(false)
    }
  } else {
    console.log('🎯 [焦点] localStorage 中无照片数据')
  }
}

onMounted(async () => {
  console.log('🚀 [onMounted] PhotoPreview: 照片预览页面已加载')
  console.log('🚀 [onMounted] 当前路由查询参数:', route.query)

  // 调用调试方法
  debugLocalStorage()

  // 检查 localStorage 中的数据
  const currentSessionPhotosDataStr = localStorage.getItem('currentSessionPhotosData')
  const currentSessionPhotoIds = localStorage.getItem('currentSessionPhotoIds')
  console.log('🚀 [onMounted] localStorage 中的照片数据:', {
    hasPhotosData: !!currentSessionPhotosDataStr,
    hasPhotoIds: !!currentSessionPhotoIds,
    photosDataLength: currentSessionPhotosDataStr ? JSON.parse(currentSessionPhotosDataStr).length : 0
  })

  // 初始加载照片数据
  console.log('🚀 [onMounted] 开始初始加载照片数据')
  await loadPhotosFromStorage(false) // 改为 false，不清空现有照片

  // 监听页面可见性变化
  document.addEventListener('visibilitychange', handleVisibilityChange)

  // 监听窗口焦点变化
  window.addEventListener('focus', handleWindowFocus)
})

// 组件卸载时清理事件监听器
import { onUnmounted } from 'vue'

onUnmounted(() => {
  document.removeEventListener('visibilitychange', handleVisibilityChange)
  window.removeEventListener('focus', handleWindowFocus)
})
</script>
<style sc oped>
.photo-preview {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
}

/* 顶部操作区样式 */
.preview-header {
  height: 60px;
  background: #fff;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.back-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  background: none;
  border: none;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 6px;
  transition: background-color 0.3s;
  color: #606266;
}

.back-btn:hover {
  background-color: #f5f7fa;
}

.back-icon {
  width: 20px;
  height: 20px;
}

.back-text {
  font-size: 14px;
}

.task-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.cancel-btn {
  background: #fff;
  border: 1px solid #dcdfe6;
  color: #606266;
  padding: 8px 20px;
  font-size: 14px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.cancel-btn:hover {
  background: #f5f7fa;
  border-color: #c0c4cc;
}

.confirm-btn {
  background: #409EFF;
  border: 1px solid #409EFF;
  color: #fff;
  padding: 8px 20px;
  font-size: 14px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.confirm-btn:hover {
  background: #66b1ff;
  border-color: #66b1ff;
}

.confirm-btn:disabled {
  background: #c0c4cc;
  border-color: #c0c4cc;
  cursor: not-allowed;
}

/* 任务名称输入框样式 */
.task-name-input {
  margin-right: 12px;
}

.task-name-field {
  width: 200px;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  color: #606266;
  background: #fff;
  transition: border-color 0.3s;
}

.task-name-field:focus {
  outline: none;
  border-color: #409EFF;
}

.task-name-field::placeholder {
  color: #c0c4cc;
}

/* 内容区域样式 */
.content-area {
  flex: 1;
  display: flex;
  overflow: hidden;
}

/* 左侧预览区域 */
.preview-sidebar {
  width: 220px;
  background: #fff;
  border-right: 1px solid #e4e7ed;
  padding: 20px 16px;
  overflow-y: auto;
}

.preview-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.preview-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  cursor: pointer;
  transition: all 0.3s;
  border-radius: 8px;
  border: 2px solid transparent;
}

/* .preview-item:hover {
  background-color: #f5f7fa;
} */


.preview-number {
  flex-shrink: 0;
  width: 10px;
  height: 32px;
  color: #595959;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: 600;
  margin-top: 4px;
}

.preview-image {
  flex: 1;
  height: 120px;
  overflow: hidden;
  background: #fff;
  /* border: 1px solid #e4e7ed; */
}



.thumbnail-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.thumbnail-placeholder {
  width: 100%;
  height: 100%;
  padding: 8px;
  background: #fff;
}

.thumbnail-content {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.thumbnail-header {
  font-size: 10px;
  font-weight: 600;
  text-align: center;
  margin-bottom: 6px;
  color: #333;
}

.thumbnail-lines {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 3px;
  justify-content: center;
}

.line {
  height: 1px;
  background: #ddd;
  width: 100%;
}

/* 右侧主显示区域 */
.main-display {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 20px;
}

.image-container {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.main-image {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.main-photo {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.image-placeholder {
  max-width: 100%;
  max-height: 100%;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 30px;
  overflow: auto;
}

/* 模拟试卷内容样式 */
.paper-content {
  width: 100%;
  font-size: 14px;
  color: #333;
  line-height: 1.6;
}

.paper-header {
  text-align: center;
  margin-bottom: 30px;
  border-bottom: 2px solid #333;
  padding-bottom: 15px;
}

.paper-header h3 {
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 8px 0;
}

.paper-header h4 {
  font-size: 18px;
  font-weight: 700;
  margin: 0;
}

.question-section {
  margin-bottom: 25px;
}

.question-row {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 15px;
  justify-content: center;
}

.question-label {
  font-size: 14px;
  font-weight: 500;
}

.answer-box {
  width: 80px;
  height: 25px;
  border: 1px solid #333;
  border-radius: 2px;
}

.question-content p {
  font-weight: 600;
  margin: 0 0 15px 0;
  font-size: 15px;
}

.calculation-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-top: 15px;
}

.calc-item {
  font-size: 14px;
  padding: 8px;
  text-align: center;
  background: #f8f9fa;
  border-radius: 4px;
}

/* 页数进度展示 */
.page-progress {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 12px;
  height: 50px;
  border-radius: 8px;
  padding: 0 20px;
}

.nav-btn {
  width: 32px;
  height: 32px;
  border: none;
  background: transparent;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  color: #606266;
  transition: all 0.3s;
}

.nav-btn:hover:not(:disabled) {
  color: #409EFF;
}

.nav-btn:disabled {
  color: #c0c4cc;
  cursor: not-allowed;
}

.current-page {
  min-width: 60px;
  height: 28px;
  background: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  font-weight: 600;
  color: #595959;
}

.page-separator {
  font-size: 16px;
  color: #909399;
  margin: 0 4px;
}

.total-pages {
  font-size: 16px;
  color: #909399;
}

/* 再拍一页按钮样式 */
.add-more-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  cursor: pointer;
  transition: all 0.3s;
  padding: 8px;
  border-radius: 8px;
  border: 2px solid transparent;
}

.add-more-item:hover {
  background-color: #f5f7fa;
}

.add-more-number {
  flex-shrink: 0;
  width: 10px;
  color: #595959;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: 600;
  margin-top: 4px;
}

.add-more-image {
  flex: 1;
  height: 120px;
  overflow: hidden;
  background: #fafafa;
  border: 2px dashed #d9d9d9;
  display: flex;
  align-items: center;
  justify-content: center;
}

.add-more-image:hover {
  border-color: #409EFF;
  background: #f0f9ff;
}

.add-more-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.add-more-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
}

.add-more-icon svg {
  width: 24px;
  height: 24px;
}

.add-more-text {
  font-size: 14px;
  color: #8C9CAD;
  font-weight: 500;
}

.add-more-item:hover .add-more-text {
  color: #409EFF;
}

.add-more-item:hover .add-more-icon svg path {
  stroke: #409EFF;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .preview-sidebar {
    width: 160px;
  }

  .main-display {
    padding: 16px;
  }
}

@media (max-width: 768px) {
  .preview-navbar {
    padding: 0 16px;
  }

  .preview-sidebar {
    width: 120px;
    padding: 16px 12px;
  }

  .preview-image {
    height: 100px;
  }

  .main-display {
    padding: 12px;
  }

  .task-name {
    font-size: 14px;
  }

  .back-icon {
    width: 16px;
    height: 16px;
  }
}

@media (max-width: 480px) {
  .content-area {
    flex-direction: column;
  }

  .preview-sidebar {
    width: 100%;
    height: 140px;
    border-right: none;
    border-bottom: 1px solid #e4e7ed;
  }

  .preview-list {
    flex-direction: row;
    overflow-x: auto;
    padding-bottom: 8px;
  }

  .preview-item {
    flex-shrink: 0;
    width: 100px;
  }

  .preview-image {
    height: 100px;
  }
}
</style>